package my.mybatis.common.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;


public class ServletUtils
{
	private ServletUtils(){}

	/**
	 * 根据key获取request中value值
	 * @param request
	 * @param sKey
	 * @return 不会返回null，但是会返回<code>""</code>
	 */
	public static String getRequestValue(HttpServletRequest request, String sKey)
	{
		if (request.getParameter(sKey) != null)
			return request.getParameter(sKey);
		else
			return "";
	}

	/**
	 * 根据key获取request中values值
	 * @param request
	 * @param sKey
	 * @return 不会返回null，但是会返回<code>""</code>
	 */
	public static String[] getRequestValues(HttpServletRequest request, String sKey)
	{
		if (request.getParameterValues(sKey) != null)
			return request.getParameterValues(sKey);
		else
			return new String[0];
	}

	/**
	 * 从cookie中获取值
	 * @param request
	 * @param sName
	 * @return 不会返回null 如果找到就返回，如果找不到<code>""</code>
	 */
	public static String getCookieValue(HttpServletRequest request, String sName)
	{
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0)
			for (Cookie cookie : cookies)
				if (cookie != null && cookie.getName() != null && sName.equalsIgnoreCase(cookie.getName()))
					return cookie.getValue();
		return "";
	}

	/**
	 * 设置cookie的值
	 * @param request
	 * @param response
	 * @param sName
	 * @param sValue
	 * @param sDomain
	 * @param iTime
	 */
	public static void setCookieValue(HttpServletRequest request, HttpServletResponse response, String sName, String sValue, String sDomain, int iTime)
	{
		Cookie cookie = new Cookie(sName, sValue);
		cookie.setMaxAge(iTime);
		cookie.setPath("/");
		if (sDomain != null && !"".equals(sDomain))
			cookie.setDomain(sDomain);
		response.addCookie(cookie);
	}

	/**
	 * 获取客户端ip
	 * @param request
	 * @return 不会返回null 有可能返回<code>""</code>
	 */
	public static String getRemoteAddr(HttpServletRequest request)
	{
		String sIP = request.getHeader("x-forwarded-for");

		if (StringUtils.isEmpty(sIP) || "unknown".equalsIgnoreCase(sIP))
			sIP = request.getHeader("Proxy-Client-IP");

		if (StringUtils.isEmpty(sIP) || "unknown".equalsIgnoreCase(sIP))
			sIP = request.getHeader("WL-Proxy-Client-IP");

		if (StringUtils.isEmpty(sIP) || "unknown".equalsIgnoreCase(sIP))
			sIP = request.getRemoteAddr();

		if (!StringUtils.isEmpty(sIP))
		{
			int iIndexOf = sIP.indexOf(",");
			if (iIndexOf != -1)
				sIP = sIP.substring(0, iIndexOf);
		}

		return sIP == null ? "" : sIP;
	}

	/**
	 * 根据request获取token
	 * @param request
	 * @return 会返回null
	 */
	public static String getUserSessionToken(HttpServletRequest request, String session_header_token_key){
		String token = null;
		// 先从header中取token，普通请求
		if (request != null) {
			token = request.getHeader(session_header_token_key);
			//为防止前端在设置用户token的key值可能有大小写的区分，统一转换小写匹配
			if (StringUtils.isEmpty(token)) {
				if (request.getHeaderNames() != null) {
					Enumeration<String> enumStr = request.getHeaderNames();
					while (enumStr.hasMoreElements()) {
						String haederKey = enumStr.nextElement();
						if(!StringUtils.isEmpty(haederKey)){
							if(session_header_token_key.toLowerCase().equals(haederKey.toLowerCase())){
								token = request.getHeader(haederKey);
								break;
							}
						}
					}
				}
			}
			// 批量上传，token放到cookie中，从cookie中获取
			if(StringUtils.isEmpty(token))
				token = getCookieValue(request,session_header_token_key);
		}
		return token;
	}

	/**
	 * 拦截器中返回异常，要设置跨域响应头
	 * @param request
	 * @param response
	 */
	public static void setResponseHeader(HttpServletRequest request, HttpServletResponse response)
	{
		response.setHeader("Access-Control-Allow-Credentials","true");
		String referer = request.getHeader("Referer");
		if(!StringUtils.isEmpty(referer) && referer.endsWith("/"))
			referer = referer.substring(0,referer.length()-1);
		response.setHeader("Access-Control-Allow-Origin",referer);
	}
}